package com.atguigu.spzx.manager.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.spzx.common.service.exception.GuiguException;
import com.atguigu.spzx.common.util.AuthContextUtil;
import com.atguigu.spzx.manager.mapper.SysUserMapper;
import com.atguigu.spzx.manager.service.SysUserService;
import com.atguigu.spzx.model.dto.system.LoginDto;
import com.atguigu.spzx.model.dto.system.SysUserDto;
import com.atguigu.spzx.model.entity.system.SysUser;
import com.atguigu.spzx.model.vo.common.ResultCodeEnum;
import com.atguigu.spzx.model.vo.system.LoginVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    @Transactional(readOnly = true)
    public LoginVo login(LoginDto loginDto) {
        // 校验验证码是否正确
        String captcha = loginDto.getCaptcha();     // 用户输入的验证码
        String codeKey = loginDto.getCodeKey();     // redis中验证码的数据key
        if (StrUtil.isEmpty(captcha)){
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // redis中获取验证码
        String redisCode = redisTemplate.opsForValue().get("user:code:validatecode:" + codeKey);
        if(StrUtil.isEmpty(redisCode) || !StrUtil.equalsIgnoreCase(redisCode , captcha)) {
            throw new GuiguException(ResultCodeEnum.CODE_ERROR) ;
        }
        // 删除验证码
        redisTemplate.delete("user:code:validatecode:" + codeKey) ;
        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();
        if (StrUtil.isEmpty(userName) || StrUtil.isEmpty(password)) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
        // 根据用户名查询用户
        SysUser sysUser = sysUserMapper.selectByUserName(userName);
        if (sysUser == null) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_NOT_EXSIT);
        }
        // 验证密码是否正确
        String md5InputPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!md5InputPassword.equals(sysUser.getPassword())) {
            throw new GuiguException(ResultCodeEnum.PASSWORD_ERROR);
        }
        if (sysUser.getStatus().intValue() == 0) {
            throw new GuiguException(ResultCodeEnum.ACCOUNT_STOP);
        }
        // 生成令牌，保存数据到Redis中
        String token = UUID.randomUUID().toString().replace("-", "");
        redisTemplate.opsForValue().set("user:login:" + token, JSONObject.toJSONString(sysUser), 30, TimeUnit.MINUTES);

        // 构建响应结果对象
        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setRefresh_token("");

        // 返回
        return loginVo;
    }

    @Override
    public SysUser getUserInfo(String token) {
     /*   // 根据token去redis获取用户信息
        String strUser = redisTemplate.opsForValue().get("user:login:" + token);
        // 获取的json数据转为实体类对象
        return JSONObject.parseObject(strUser, SysUser.class);*/
        SysUser sysUser = AuthContextUtil.get();
        return sysUser;
    }

    @Override
    public void logout(String token) {
        redisTemplate.delete("user:login:"+token);
    }

    @Override
    @Transactional(readOnly = true)
    public PageInfo<SysUser> findByPage(Integer pageNum, Integer pageSize, SysUserDto sysUserDto) {
        PageHelper.startPage(pageNum,pageSize);
        List<SysUser> sysUserList =  sysUserMapper.selectByPage(sysUserDto);
        return new PageInfo<>(sysUserList);
    }

    @Override
    @Transactional(readOnly = true)
    public SysUser findById(Long id) {
        return sysUserMapper.selectById(id);
    }

    @Override
    public void changeSysUser(SysUser sysUser) {
        sysUserMapper.updateSysUser(sysUser);
    }

    @Override
    public void addSysUser(SysUser sysUser) {
        sysUser.setPassword(DigestUtils.md5DigestAsHex(sysUser.getPassword().getBytes()));
        sysUserMapper.insert(sysUser);
    }

    @Override
    public void removeSysUser(Integer id) {
        sysUserMapper.deleteSysUser(id);
    }

}